#include "widget.h"
#include "ui_widget.h"
#include <QTimer>
#include <QLabel>
#include <QDockWidget>
#include <QDebug>
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setWindowTitle("雷达中频采集软件v1.0");

    receiver=new UdpMulticastReceiver();
    // 启动数据接收
    receiver->start();

    QTimer *timer = new QTimer(this);
    timer->start(100); // 每1000毫秒（1秒）触发一次
    connect(timer, &QTimer::timeout, this, &Widget::updateLabel);

    IQ_signal_init();

    connect(ui->pushButton_6, &QPushButton::clicked, this, &Widget::onPushButtonClicked);

    ui->logTabWidget->setSelectionMode(QAbstractItemView::SingleSelection);
    connect(ui->logTabWidget, &QTableWidget::itemClicked, this, &Widget::onItemSelected);
    connect(ui->openButton, &QPushButton::clicked, this, &Widget::openFile);
    initHeader(QStringList() << "序号" << "到达时间(h:m:s)"<< "到达时间(ns)"<< "PW(us)" << "PA(dBm)"<< "RF(MHz)" << "DOA(°）"<< "脉冲起始点" << "脉冲终止点");
    currentPageSum = 100;
    currentPage = 1;

    for (int i = 1; i <= 100; i++) {
        QVariantList varList;
        varList << i << QString(" ")<< QString(" ")<< QString(" ")<< QString(" ")
                << QString(" ")<< QString(" ")<< QString(" ")<< QString(" ");
        m_lDatas.push_back(varList);
    }
    addLogDatas(m_lDatas);
}

Widget::~Widget()
{
    delete ui;
}
void Widget::updateLabel() {
    // 假设wenjian_changdu是一个qint64类型的变量
    qint64 wenjian_changdu = receiver->wenjian_changdu;

    // 将数字转换为字符串
    QString text = QString::number(wenjian_changdu);

    // 设置QLabel的文本
    ui->label_2->setText(text);
}

void Widget::openFile() {
    m_lDatas.clear(); // 清空之前的数据

    // 打开文件选择对话框
    QString filePath = QFileDialog::getOpenFileName(this, "Open File", QDir::currentPath());
    if (filePath.isEmpty()) {
        qDebug() << "No file selected.";
        return;
    }
    pls_flug=0;
    wenjianming = filePath.chopped(4);
    // 文件基本操作
    QFile file(filePath);

    if (!file.open(QIODevice::ReadOnly)) {
        qDebug() << "Failed to open the file:" << file.errorString();
        return;
    }

    QByteArray allData = file.readAll();
    file.close();
    //qDebug()<<allData;

    if (allData.isEmpty()) {
        qDebug() << "The file is empty.";
        return;
    }

    // 数据解析
    int chunkSize = 40; // 每个数据块的大小
    int tiaoshu=0;
    for (int i = 0; i < allData.size(); i += chunkSize) {
        QByteArray chunk = allData.mid(i, chunkSize); // 获取每个数据块
        if (chunk.size() < chunkSize) {
            // 如果数据块大小不正确，跳过
            break; // 使用 break 退出循环，因为剩余的数据不足一个数据块
        }
        quint16 first;
        qint64 second;
        quint32 a1,a2,a3,a4,seventh, eighth;

        QVariantList varList;
        QDataStream stream(&chunk, QIODevice::ReadOnly);
        stream.setByteOrder(QDataStream::LittleEndian); // 根据数据的实际字节序设置
        // 读取数据

        tiaoshu++;
        stream >> first>> second>>a1>>a2>>a3>>a4>>seventh>>eighth;

        int time1=second%1000000000;
        qint64 time2=second/1000000000;
        QDateTime dtObject = QDateTime::fromSecsSinceEpoch(time2);
        QString format = "yyyy-MM-dd hh:mm:ss";
        QString time3 = dtObject.toString(format);
        QString time4 = time3.mid(11);


        float third, fourth, fifth, sixth;

        unsigned char third_f[] = {static_cast<unsigned char>(chunk.at(10)), static_cast<unsigned char>(chunk.at(11)),
                                   static_cast<unsigned char>(chunk.at(12)), static_cast<unsigned char>(chunk.at(13))};
        unsigned char* p1 = (unsigned char*)&third;
        for (size_t i=0; i<sizeof(float); i++) {
            *(p1+i) = third_f[i];
        }

        unsigned char fourth_f[] = {static_cast<unsigned char>(chunk.at(14)), static_cast<unsigned char>(chunk.at(15)),
                                    static_cast<unsigned char>(chunk.at(16)), static_cast<unsigned char>(chunk.at(17))};
        unsigned char* p2 = (unsigned char*)&fourth;
        for (size_t i=0; i<sizeof(float); i++) {
            *(p2+i) = fourth_f[i];
        }

        unsigned char fifth_f[] = {static_cast<unsigned char>(chunk.at(18)), static_cast<unsigned char>(chunk.at(19)),
                                   static_cast<unsigned char>(chunk.at(20)), static_cast<unsigned char>(chunk.at(21))};
        unsigned char* p3 = (unsigned char*)&fifth;
        for (size_t i=0; i<sizeof(float); i++) {
            *(p3+i) = fifth_f[i];
        }

        unsigned char sixth_f[] = {static_cast<unsigned char>(chunk.at(22)), static_cast<unsigned char>(chunk.at(23)),
                                   static_cast<unsigned char>(chunk.at(24)), static_cast<unsigned char>(chunk.at(25))};
        unsigned char* p4 = (unsigned char*)&sixth;
        for (size_t i=0; i<sizeof(float); i++) {
            *(p4+i) = sixth_f[i];
        }

        if(pls_flug==0)
        {
            pls_num=seventh;
            pls_flug=1;
        }
        // 添加到列表
        varList.append(tiaoshu);
        varList.append(time4);
        varList.append(time1);
        varList.append(third);
        varList.append(fourth);
        varList.append(fifth);
        varList.append(sixth);
        varList.append(seventh);
        varList.append(eighth);

        m_lDatas.push_back(varList);
    }

    // 处理数据
    addLogDatas(m_lDatas);
}
void Widget::IQ_signal_init(void)
{
    IQ_signal = ui->iqboxing; //创建一个画图指针
    IQ_signal->setInteractions(QCP::iRangeDrag|QCP::iRangeZoom);//可拖拽+可滚轮缩放
    IQ_signal->axisRect()->setRangeZoomFactor(1.2,1);//x方向为1.2 y为1 是不改变。
    IQ_signal->setBackground(QBrush(QColor(50, 50, 50)));
    IQ_signal->xAxis->setBasePen(QPen(Qt::black, 1));  // 轴线的画笔
    IQ_signal->xAxis->setTickPen(QPen(Qt::green, 1));  // 轴刻度线的画笔
    IQ_signal->xAxis->setSubTickPen(QPen(Qt::lightGray, 1)); // 轴子刻度线的画笔
    IQ_signal->xAxis->setTickLabelColor(Qt::green);  // 轴刻度文字颜色
    IQ_signal->yAxis->setBasePen(QPen(Qt::black, 1));  // 轴线的画笔
    IQ_signal->yAxis->setTickPen(QPen(Qt::green, 1));  // 轴刻度线的画笔
    IQ_signal->yAxis->setSubTickPen(QPen(Qt::lightGray, 1)); // 轴子刻度线的画笔
    IQ_signal->yAxis->setTickLabelColor(Qt::green);  // 轴刻度文字颜色
    IQ_signal->xAxis->setLabel("时间us");
    IQ_signal->xAxis->setLabelColor(Qt::green);   // 轴标签颜色
    IQ_signal->yAxis->setLabel("幅度");
    IQ_signal->yAxis->setLabelColor(Qt::green);   // 轴标签颜色
    IQ_signal->addGraph();
    IQ_signal->graph(0)->setPen(QPen(Qt::yellow));//设置曲线的颜色
    IQ_signal->graph(0)->setName("I信号");//曲线0名称
    IQ_signal->addGraph();
    IQ_signal->graph(1)->setPen(QPen(Qt::red));//设置曲线的颜色
    IQ_signal->graph(1)->setName("Q信号");//曲线1名称
    IQ_signal->xAxis->setRange(0,100.0);
    IQ_signal->yAxis->setRange(-10000,10000);
    IQ_signal->rescaleAxes();//自适应大小
    IQ_signal->legend->setVisible(true);

}
void Widget::updataPage()
{
    if (m_lDatas.size() <= 100) {
        pageSum = 1;
    }
    if ((m_lDatas.size() % 100) == 0) {
        pageSum = m_lDatas.size() / 100;

    }
    else {
        pageSum = (m_lDatas.size() / 100) + 1;
    }

    ui->label->setText(QString("%1/%2").arg(currentPage).arg(pageSum));
}

void Widget::updataPageData()
{
    if (currentPage == 0) {
        return;
    }

    //获取具体下标 （当前页号*当前页的总数）-当前页的总数）= 某一页的第一个的具体数据下标
    int index = (currentPage * currentPageSum) - currentPageSum;


    //删除
    for(int row = ui->logTabWidget->rowCount() - 1;row >= 0; row--)
    {
        ui->logTabWidget->removeRow(row);
    }

    int i = 0;
    for (; index < m_lDatas.size(); ++index) {
        if (index >= (currentPage * currentPageSum)) {
            break;
        }

        int rowcount = ui->logTabWidget->rowCount();
        ui->logTabWidget->insertRow(rowcount);

        QVariantList varList = m_lDatas.at(index);

        for (int j = 0; j < varList.size(); ++j) {
            QTableWidgetItem* item = new QTableWidgetItem();
            item->setData(0, varList.at(j));
            item->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
            ui->logTabWidget->setItem(i, j, item);
        }
        i++;
    }
}

void Widget::onPushButtonClicked()
{
    clickCount++; // 增加点击计数

    if (clickCount % 2 == 0) {
        receiver->stop_wt();// 偶数次点击
        ui->pushButton_6->setText("开始记录");
    } else {
        receiver->start_wt(); // 奇数次点击
        ui->pushButton_6->setText("停止记录");
    }
}
void Widget::onItemSelected(QTableWidgetItem* item) {
    if (!item) {
        return;
    }
    int selectedRow = item->row();
    ui->logTabWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
    // 如果需要，也可以获取列：int selectedColumn = item->column();
    // 获取选中行的所有数据
    QVariantList rowData;
    for (int col = 0; col < ui->logTabWidget->columnCount(); ++col) {
        QTableWidgetItem* cellItem = ui->logTabWidget->item(selectedRow, col);
        if (cellItem) {
            rowData.append(cellItem->data(0));
        }
    }

    QFile file(wenjianming + ".dat");
    if (!file.open(QIODevice::ReadOnly)) {
        qDebug() << "Failed to open file:" << file.errorString();
        return;
    }
    // 从文件的第20字节开始读取，到第1000个停止；
    int length = ((rowData.at(8).toUInt() - rowData.at(7).toUInt()+1)*4);
    if (length <= 0) {
        return;
    }
    int a=((rowData.at(6).toUInt()-pls_num)*4);
    file.seek(a); // 将文件的读写指针移动到文件的第20字节位置。这是为了从第20字节开始读取数据。
    QByteArray data(length, 0);
    QByteArray group1;
    QByteArray group2;

    // 读取数据到data中
    if (file.read(data.data(), length) != length) {
        qDebug() << "Failed to read the correct amount of data from file.";
        file.close();
        return;
    }

    file.close(); // 关闭文件
    if (data.size() >= 2) {
        for (int i = 0; i < data.size(); i += 4) {
            // 存入第i和第i+1个字节到group1
            group1.append(data.mid(i, 2));
            // 存入第i+2和第i+3个字节到group2
            group2.append(data.mid(i + 2, 2));
        }
    }

    ISig_show(group1);
    QSig_show(group2);

}
//画I图
void Widget::ISig_show(QByteArray ba)
{
    //qDebug()<<ba;
    QVector<double> time;
    QVector<double> data;
    int dianshu_jishuq=0;
    int xzhou=0;
    if (ba.size() >= 2) {
        // 初始化指针或索引来遍历QByteArray
        char* ptr = ba.data();
        // 循环遍历QByteArray，步长为2（因为我们每次读取2个字节）
        for (int i = 0; i < ba.size(); i += 2) {
            time<<i/500.0;
            // 从当前位置开始的2个字节
            short value = *reinterpret_cast<short*>(ptr + i);

            // 将short类型的值转换为double类型
            data<<static_cast<double>(value);
            dianshu_jishuq++;
            if(dianshu_jishuq==250)
            {
                dianshu_jishuq=0;
                xzhou++;
            }
        }
    } else {
        qDebug() << "Not enough data to read a short.";
    }

    IQ_signal->xAxis->setRange(0,xzhou);
    IQ_signal->graph(0)->setData(time,data);
    IQ_signal->replot();
}
//画Q图
void Widget::QSig_show(QByteArray ba)
{
    //qDebug()<<ba;
    QVector<double> time;
    QVector<double> data;

    if (ba.size() >= 2) {
        // 初始化指针或索引来遍历QByteArray
        char* ptr = ba.data();

        // 循环遍历QByteArray，步长为2（因为我们每次读取2个字节）
        for (int i = 0; i < ba.size(); i += 2) {
            time<<i/500.0;
            // 从当前位置开始的2个字节
            short value = *reinterpret_cast<short*>(ptr + i);

            // 将short类型的值转换为double类型
            data<<static_cast<double>(value);
        }
    } else {
        qDebug() << "Not enough data to read a short.";
    }
    IQ_signal->graph(1)->setData(time,data);
    IQ_signal->replot();
}
void Widget::initHeader(const QStringList &headers)
{
    ui->logTabWidget->setColumnCount(headers.size());
    ui->logTabWidget->setHorizontalHeaderLabels(headers);
    ui->logTabWidget->verticalHeader()->setHidden(false);

    ui->logTabWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->logTabWidget->setColumnWidth(0, 20);
    ui->logTabWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);    //x先自适应宽度

    QHeaderView *header = ui->logTabWidget->verticalHeader();
    header->setHidden(true);// 隐藏行号
}

void Widget::addLogData(const QVariantList &data)
{
    m_lDatas.append(data);
    updataPageData();
    updataPage();
}

void Widget::addLogDatas(const QList<QVariantList> &datas)
{
    m_lDatas = datas;
    currentPage = 1;
    updataPageData();
    updataPage();
}


void Widget::on_pushButton_3_clicked()
{
    //首页
    currentPage = 1;
    updataPageData();
    updataPage();
}

void Widget::on_pushButton_clicked()
{
    //上一页
    if (currentPage == 1) {
        return;
    }

    currentPage--;
    updataPageData();
    updataPage();
}

void Widget::on_pushButton_2_clicked()
{
    //下一页
    if (currentPage >= pageSum) {
        return;
    }
    currentPage++;
    updataPageData();
    updataPage();
}

void Widget::on_pushButton_4_clicked()
{
    //尾页
    currentPage = pageSum;
    updataPageData();
    updataPage();

}

void Widget::on_pushButton_5_clicked()
{
    //跳转
    if (ui->spinBox->value() > pageSum
            || currentPage == ui->spinBox->value()
            || ui->spinBox->value() == 0
            || pageSum == 1) {
        return;
    }
    currentPage = ui->spinBox->value();
    updataPageData();
    updataPage();
}

